package com.mcintyret.site.journal.database;

import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.util.List;

/**
 * User: mcintyret2
 * Date: 15/04/2012
 */
public abstract class AbstractHibernateDao<T> {

    private final Class<T> clazz;
    private final String type;

    protected AbstractHibernateDao(Class<T> clazz) {
        this.clazz = clazz;
        type = clazz.getSimpleName();
    }

    protected SessionFactory sessionFactory;

    protected T get(Serializable id) {
        return (T) sessionFactory.getCurrentSession().get(clazz, id);
    }

    public List<T> getAll() {
        return (List<T>) sessionFactory.getCurrentSession().createQuery("from " + type);
    }

    public List<T> getAllWhere(String query) {
        return (List<T>) sessionFactory.getCurrentSession().createQuery("from " + type + " where " + query).list();
    }

    public int getCount() {
        String query = "select count(*) from " + type;
        return ((Long) sessionFactory.getCurrentSession().createQuery(query).uniqueResult()).intValue();
    }

    public int getCountWhere(String where) {
        String query = "select count(*) from " + type + " where " + where;
        return ((Long) sessionFactory.getCurrentSession().createQuery(query).uniqueResult()).intValue();
    }

    public void delete(T t) {
        sessionFactory.getCurrentSession().delete(t);
    }

    public Serializable addAndGetId(T t) {
        return sessionFactory.getCurrentSession().save(t);
    }

    public void add(T t) {
        sessionFactory.getCurrentSession().persist(t);
    }

    public void flushSession() {
        sessionFactory.getCurrentSession().flush();
    }

    protected Class<T> getClazz() {
        return clazz;
    }



    protected abstract void setSessionFactory(SessionFactory sessionFactory);
}
